/* Copyright 2014 Nate Eisner
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package edu.uwp.kcwm;

import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

public class URLCheckerAsync extends AsyncTask<String,Void,Boolean>{
	Handler mHandler;

	/**
	 * Constructor
	 * @param h
	 */
	public URLCheckerAsync (Handler h) {
		this.mHandler = h;
	}

	/**
	 * Checks if content exists at a given url
	 */
	@Override
	protected Boolean doInBackground(String... params) {
		boolean result = true;
		try {
			// Open connection to the remote server
			URL url = new URL(params[0]);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			int code = connection.getResponseCode();
			//if url exists
			if (code == 200)
				result = true;
			else
				result = false;
		}
		catch (Exception e) {
			e.printStackTrace();
			result = false;
		}
		return result;
	}
	
	/**
	 * Returns the result of url check
	 */
	@Override
	protected void onPostExecute(Boolean result) {
	    //send msg to main thread
	    super.onPostExecute(result);
	    Message msg=new Message();
        msg.obj = result;
		mHandler.sendMessage(msg);
	}
}